package com.renwei.yunlong.fragment;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.CompanySelectAdapter;
import com.renwei.yunlong.adapter.OwnerServiceFloderListAdapter;
import com.renwei.yunlong.adapter.ProjectChooseAdapter;
import com.renwei.yunlong.adapter.ServerServiceFloderListAdapter;
import com.renwei.yunlong.adapter.VpFragmentAdapter;
import com.renwei.yunlong.base.BaseLazyFragment;
import com.renwei.yunlong.bean.CompanySelectBean;
import com.renwei.yunlong.bean.OwnerChooseServiceFloderBean;
import com.renwei.yunlong.bean.ScreenBean;
import com.renwei.yunlong.bean.ServerChooseServiceFloderBean;
import com.renwei.yunlong.event.ChartPasgeRefreseEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.DateTimeUtils;
import com.renwei.yunlong.utils.DialogUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.UtilList;
import com.renwei.yunlong.view.NoScrollViewPager;
import com.renwei.yunlong.view.SimpleOptionView;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import io.github.xudaojie.qrcodelib.zxing.DensityUtils;

/**
 * Created by wangqi on 2018/1/5.
 */

public class ChartFragment extends BaseLazyFragment implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, HttpTaskListener, TimePickerView.OnTimeSelectListener {

    @Bind(R.id.rb_resolution)
    RadioButton rbResolution;
    @Bind(R.id.rb_sla)
    RadioButton rbSla;
    @Bind(R.id.rb_satisfied)
    RadioButton rbSatisfied;
    @Bind(R.id.rb_complaint)
    RadioButton rbComplaint;
    @Bind(R.id.rg_chart)
    RadioGroup rgChart;
    @Bind(R.id.viewPager)
    NoScrollViewPager viewPager;
    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    private List<Fragment> list;
    private PopupWindow filterPopWindow;
    private PopupWindow chooseWindow;
    private TextView tvTimeEnd, tvCategory, tvService, tvTimeStart, tvProject;
    private TimePickerView pvTime;
    private String targetCompanyCode;
    private String targetProjectId;
    private String targetServiceCode;
    private boolean isAdmin;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chat;
    }

    @Override
    public void onLazyLoad() {
        initFragments();

        rgChart.setOnCheckedChangeListener(this);
        rbResolution.toggle();

        simpleTileView.setTitle("统计报表");
        simpleTileView.setLeftImageViewVisibility(View.INVISIBLE);
        if ("1".equals(companyType)) {
            if (AppHelper.isAdminOrServerDesk(ownerBean)) {
                isAdmin = true;
            } else {
                isAdmin = false;
            }
        } else {
            if (AppHelper.isAdminOrServerDesk(serviceLoginBean)) {
                isAdmin = true;
            } else {
                isAdmin = false;
            }
        }
        if (isAdmin) {
            simpleTileView.setRightOption(R.mipmap.icon_screen, this);
        }
    }

    private void initFragments() {
        list = new ArrayList<>();
        list.add(new WorkResolutionFragment());
        list.add(new WorkSLAFragment());
        list.add(new WorkSatisfiedFragment());
        list.add(new WorkComplaintFragment());

        VpFragmentAdapter adapter = new VpFragmentAdapter(getChildFragmentManager(), list);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(4);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int id) {
        switch (id) {
            case R.id.rb_resolution:
                viewPager.setCurrentItem(0);
                break;
            case R.id.rb_sla:
                viewPager.setCurrentItem(1);
                break;
            case R.id.rb_satisfied:
                viewPager.setCurrentItem(2);
                break;
            case R.id.rb_complaint:
                viewPager.setCurrentItem(3);
                break;
            default:
                break;
        }
    }

    //----------------------------------------------------------------------------显示筛选弹窗
    private void showFilterWindow(View view) {
        if (filterPopWindow == null) {
            View contentView = LayoutInflater.from(getContext()).inflate(R.layout.popu_chat_filter, null);
            filterPopWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            filterPopWindow.setTouchable(true);
            ColorDrawable dw = new ColorDrawable(0xb0808080);
            filterPopWindow.setBackgroundDrawable(dw);
            filterPopWindow.setAnimationStyle(R.style.pop_animation_right);
            filterPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    DialogUtils.backgroundAlpha(getActivity(), 1f);
                }
            });
            initFilterView(contentView);
        }
        filterPopWindow.showAtLocation(view, Gravity.END, 0, 0);
        DialogUtils.backgroundAlpha(getActivity(), 0.5f);//0.0-1.0
    }

    private void initFilterView(View contentView) {
        tvTimeEnd = contentView.findViewById(R.id.tv_time_end);
        tvTimeStart = contentView.findViewById(R.id.tv_time_start);
        tvProject = contentView.findViewById(R.id.tv_project);
        tvService = contentView.findViewById(R.id.tv_service);
        tvCategory = contentView.findViewById(R.id.tv_categry);

        LinearLayout llProject = contentView.findViewById(R.id.ll_project);
        if ("1".equals(companyType)) {
            llProject.setVisibility(View.GONE);
        } else {
            llProject.setVisibility(View.VISIBLE);
        }
        contentView.findViewById(R.id.rl_project).setOnClickListener(this);
        contentView.findViewById(R.id.rl_service).setOnClickListener(this);
        contentView.findViewById(R.id.rl_category).setOnClickListener(this);
        contentView.findViewById(R.id.bt_confirm).setOnClickListener(this);
        contentView.findViewById(R.id.bt_reset).setOnClickListener(this);
        tvTimeStart.setOnClickListener(this);
        tvTimeEnd.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_parent:
                showFilterWindow(v);
                break;
            case R.id.rl_project:
                // TODO: 2018/1/18 项目选择
                projectChoose();
                break;
            case R.id.rl_service:
                // TODO: 2018/1/18 服务目录选择
                serviceFloderChoose();
                break;
            case R.id.rl_category:
                // TODO: 2018/1/18 企业选择
                companyChoose();
                break;
            case R.id.tv_time_start:
                break;
            case R.id.tv_time_end:
                break;
            case R.id.bt_confirm:
                EventBus.getDefault().post(new ChartPasgeRefreseEvent(targetCompanyCode, targetProjectId, targetServiceCode));
                filterPopWindow.dismiss();
                break;
            case R.id.bt_reset:
                filterPopWindow.dismiss();
                filterPopWindow = null;
                targetCompanyCode = "";
                targetProjectId = "";
                targetServiceCode = "";
                tvTimeStart.setText("查询起始");
                tvTimeEnd.setText("查询截止");
                EventBus.getDefault().post(new ChartPasgeRefreseEvent(targetCompanyCode, targetProjectId, targetServiceCode));
                break;
            case R.id.rl_back:
                chooseWindow.dismiss();
                filterPopWindow.showAtLocation(simpleTileView, Gravity.END, 0, 0);
                break;
            default:
                break;
        }
    }

    /**
     * 筛选-企业
     */
    private void companyChoose() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("exeType", "2");
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            map.put("serverName", "");
        } else if ("2".equals(companyType)) {
            map.put("useFlag", "1");
            map.put("type", "1");
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            map.put("serverName", "");
        }
        ServiceRequestManager.getManager().getCompanyChoose(getActivity(), JsonMapUtil.mapToJson(map), new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
//企业筛选
                CompanySelectBean companySelectBean = new Gson().fromJson(result, CompanySelectBean.class);
                if (companySelectBean.getMessage().getCode() == 200) {
                    View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popu_selector_layout, null);
                    RecyclerView lvPop = contentView.findViewById(R.id.rv_pop);
                    TextView tvTitle = contentView.findViewById(R.id.tv_title);
                    if ("1".equals(companyType)) {
                        tvTitle.setText("选择服务商");
                    } else {
                        tvTitle.setText("选择业主");
                    }
                    contentView.findViewById(R.id.rl_back).setOnClickListener(ChartFragment.this);
                    lvPop.setLayoutManager(new LinearLayoutManager(getActivity()));
                    List<CompanySelectBean.Rows> rows = companySelectBean.getRows();
                    CompanySelectBean.Rows rowBean = new CompanySelectBean.Rows();
                    rowBean.setServerName("全部");
                    rows.add(0, rowBean);
                    final CompanySelectAdapter adapter = new CompanySelectAdapter(getContext(), companyType);
                    adapter.setPicShow(false);
                    adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            CompanySelectBean.Rows bean = adapter.getItem(position);
                            chooseWindow.dismiss();
                            tvCategory.setText(bean.getServerName());
                            if (TextUtils.isEmpty(bean.getCompanyCode()) || !bean.getCompanyCode().equals(targetCompanyCode)) {
                                targetCompanyCode = bean.getCompanyCode();
                                targetProjectId = "";
                                tvProject.setText("全部");
                                targetServiceCode = "";
                                tvService.setText("全部");
                            }
                        }
                    });
                    lvPop.setAdapter(adapter);
                    adapter.setData(rows);
                    showPopuSelector(simpleTileView, contentView);
                }
            }

            @Override
            public void onException(int requestId, String code) {

            }
        });
    }


    //popupWindow弹框
    private void showPopuSelector(final View view, View contentView) {
        chooseWindow = new PopupWindow(contentView, DensityUtils.dp2px(getContext(), 300), ViewGroup.LayoutParams.MATCH_PARENT, true);
        chooseWindow.setTouchable(true);
        ColorDrawable dw = new ColorDrawable(0xb0808080);
        chooseWindow.setBackgroundDrawable(dw);
        chooseWindow.setAnimationStyle(R.style.pop_animation_right);

        chooseWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                filterPopWindow.showAtLocation(view, Gravity.RIGHT, 0, 0);
            }
        });
        filterPopWindow.dismiss();
        DialogUtils.backgroundAlpha(getActivity(), 0.5f);//0.0-1.0
        chooseWindow.showAtLocation(view, Gravity.RIGHT, 0, 0);
    }


    /**
     * 项目筛选
     */
    private void projectChoose() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("serviceProviderCode", targetCompanyCode);
        } else if ("2".equals(companyType)) {
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("ownerCode", targetCompanyCode);
        }
        ServiceRequestManager.getManager().getProjectChoose(getActivity(), JsonMapUtil.mapToJson(map), new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
                ScreenBean screenBean = new Gson().fromJson(result, ScreenBean.class);
                if (screenBean.getMessage().getCode() == 200) {
                    if (screenBean.getRows().size() != 0) {
                        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popu_selector_layout, null);
                        RecyclerView lvPop = contentView.findViewById(R.id.rv_pop);
                        TextView tvTitle = contentView.findViewById(R.id.tv_title);
                        tvTitle.setText("选择项目");
                        contentView.findViewById(R.id.rl_back).setOnClickListener(ChartFragment.this);
                        lvPop.setLayoutManager(new LinearLayoutManager(getActivity()));
                        final ProjectChooseAdapter adapter = new ProjectChooseAdapter(getActivity());
                        ScreenBean.RowsBean rowBean = new ScreenBean.RowsBean();
                        rowBean.setContractName("全部");
                        screenBean.getRows().add(0, rowBean);
                        adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                chooseWindow.dismiss();
                                tvProject.setText(adapter.getData().get(position).getContractName());
                                if (adapter.getData().get(position).getContractId() != 0) {
                                    targetProjectId = adapter.getData().get(position).getContractId() + "";
                                } else {
                                    targetProjectId = "";
                                }
                                targetServiceCode = "";
                                tvService.setText("全部");
                            }
                        });
                        lvPop.setAdapter(adapter);
                        adapter.addAll(screenBean.getRows());
                        showPopuSelector(simpleTileView, contentView);
                    } else {
                        showCenterInfoMsg("未查询到项目");
                    }

                } else {
                    showCenterInfoMsg(screenBean.getMessage().getMessage());
                }
            }

            @Override
            public void onException(int requestId, String code) {

            }
        });


    }


    /**
     * 选择服务目录
     */
    private void serviceFloderChoose() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
        } else if ("2".equals(companyType)) {
            map.put("contractId", targetProjectId);//项目id
            map.put("ownerCode", targetCompanyCode);//选择企业的id
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());//当前公司code
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
        }
        ServiceRequestManager.getManager().getChartService(getActivity(), JsonMapUtil.mapToJson(map), new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
                initServerFloder(result);
            }

            @Override
            public void onException(int requestId, String code) {

            }
        });
    }

    private void initServerFloder(String result) {
        ServerChooseServiceFloderBean serviceFloderBean = new Gson().fromJson(result, ServerChooseServiceFloderBean.class);
        if (serviceFloderBean != null && serviceFloderBean.getRows() != null) {
            if (UtilList.getCount(serviceFloderBean.getRows()) > 0) {

                View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popu_selector_layout, null);
                RecyclerView lvPop = contentView.findViewById(R.id.rv_pop);
                TextView tvTitle = contentView.findViewById(R.id.tv_title);
                tvTitle.setText("选择服务");
                contentView.findViewById(R.id.rl_back).setOnClickListener(ChartFragment.this);
                lvPop.setLayoutManager(new LinearLayoutManager(getActivity()));
                final ServerServiceFloderListAdapter adapter = new ServerServiceFloderListAdapter(getActivity());
                ServerChooseServiceFloderBean.RowsBean rowBean = new ServerChooseServiceFloderBean.RowsBean();
                rowBean.setDetailName("全部");
                serviceFloderBean.getRows().add(0, rowBean);
                adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        chooseWindow.dismiss();
                        if (StringUtils.value(adapter.getData().get(position).getDetailId()).length() > 0) {
                            targetServiceCode = StringUtils.value(adapter.getData().get(position).getDetailId());
                            tvService.setText(adapter.getData().get(position).getDetailName());
                        } else if (StringUtils.value(adapter.getData().get(position).getId()).length() > 0){
                            targetServiceCode =StringUtils.value(adapter.getData().get(position).getId());
                            tvService.setText(adapter.getData().get(position).getServicesDirectoryName());
                        }else{
                            targetServiceCode = "";
                        }
                    }
                });
                lvPop.setAdapter(adapter);
                adapter.addAll(serviceFloderBean.getRows());
                showPopuSelector(simpleTileView, contentView);
            } else {
                showCenterInfoMsg("未查询到相关服务");
            }
        } else {
            showCenterInfoMsg("未查询到相关服务");
        }
    }

    private void initOwnerFloder(String result) {
        OwnerChooseServiceFloderBean ownerChooseServiceFloderBean = new Gson().fromJson(result, OwnerChooseServiceFloderBean.class);
        if (ownerChooseServiceFloderBean != null && ownerChooseServiceFloderBean.getRows() != null) {
            if (UtilList.getCount(ownerChooseServiceFloderBean.getRows()) > 0) {

                View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popu_selector_layout, null);
                RecyclerView lvPop = contentView.findViewById(R.id.rv_pop);
                TextView tvTitle = contentView.findViewById(R.id.tv_title);
                tvTitle.setText("选择服务");
                contentView.findViewById(R.id.rl_back).setOnClickListener(ChartFragment.this);
                lvPop.setLayoutManager(new LinearLayoutManager(getActivity()));
                final OwnerServiceFloderListAdapter adapter = new OwnerServiceFloderListAdapter(getActivity());
                OwnerChooseServiceFloderBean.RowsBean rowBean = new OwnerChooseServiceFloderBean.RowsBean();
                rowBean.setServicesDirectoryName("全部");
                ownerChooseServiceFloderBean.getRows().add(0, rowBean);
                adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        chooseWindow.dismiss();
                        tvService.setText(adapter.getData().get(position).getServicesDirectoryName());
                        if (adapter.getData().get(position).getId() != 0) {
                            targetServiceCode = StringUtils.value(adapter.getData().get(position).getId());
                        } else {
                            targetServiceCode = "";
                        }
                    }
                });
                lvPop.setAdapter(adapter);
                adapter.addAll(ownerChooseServiceFloderBean.getRows());
                showPopuSelector(simpleTileView, contentView);
            } else {
                showCenterInfoMsg("未查询到相关服务");
            }

        } else {
            showCenterInfoMsg("未查询到相关服务");
        }
    }


    /**
     * 显示 时间选择器
     *
     * @param view
     */
    private void showPickerView(Date date, View view) {
        Calendar calendar = Calendar.getInstance();
        if (date != null) {
            calendar.setTime(date);
        }
        if (pvTime == null) {
            pvTime = new TimePickerView.Builder(getContext(), this)
                    //年月日时分秒 的显示与否，不设置则默认全部显示
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setLabel("", "", "", "", "", "")
                    .isCenterLabel(false)
                    .isDialog(true)
                    .setTitleText("选择日期")
                    .setDate(calendar)
                    .setDividerColor(Color.BLACK)
                    .setTextColorCenter(getResources().getColor(R.color.text_dark_black_color)) //设置选中项文字颜色
                    .setTextColorOut(getResources().getColor(R.color.color_666666))
                    .setDividerColor(getResources().getColor(R.color.color_999999))
                    .setCancelText("取消")
                    .setCancelColor(getResources().getColor(R.color.color_999999))
                    .setSubmitText("确定")
                    .setSubmitColor(getResources().getColor(R.color.blue_color))
                    .setContentSize(20)
                    .setTitleSize(17)
                    .build();
        }
        pvTime.show(view);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 5:
                break;
            default:
                break;

        }
    }

    @Override
    public void onException(int requestId, String code) {

    }

    @Override
    public void onTimeSelect(Date date, View v) {
        switch (v.getId()) {
            case R.id.tv_time_start:
                if ("查询截止".equals(tvTimeEnd.getText().toString())) {
                    tvTimeStart.setText(DateTimeUtils.date2String(date, "yyyy-MM-dd"));
                } else {
                    if (DateTimeUtils.compareTime(tvTimeEnd.getText().toString())
                            < DateTimeUtils.compareTime(DateTimeUtils.date2String(date, "yyyy-MM-dd"))) {
                        showCenterInfoMsg("结束时间不能小于开始时间");
                    } else {
                        tvTimeStart.setText(DateTimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                }
                break;
            case R.id.tv_time_end:
                if ("查询起始".equals(tvTimeStart.getText().toString())) {
                    tvTimeEnd.setText(DateTimeUtils.date2String(date, "yyyy-MM-dd"));
                } else {
                    if (DateTimeUtils.compareTime(DateTimeUtils.date2String(date, "yyyy-MM-dd")) <
                            DateTimeUtils.compareTime(tvTimeStart.getText().toString())) {
                        showCenterInfoMsg("结束时间不能小于开始时间");
                    } else {
                        tvTimeEnd.setText(DateTimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                }
                break;
            default:
                break;
        }
    }


}
